/*
 * Copyright 2008 Nordic Consulting & Development Company
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package pl.ncdc.web.login.client.ui;

import java.util.ArrayList;
import java.util.Collection;

import pl.ncdc.web.login.client.service.UserServiceAsync;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.SuggestOracle;

/**
 * The oracle suggesting user id. The suggestion is based on the
 * beginning of provided uid.
 * <p>
 * Created on Apr 17, 2008
 *
 * @author hshsce
 * @version $Id: UidSuggestOracle.java 35 2008-04-17 14:22:38Z hshsce $
 */
public class UidSuggestOracle extends SuggestOracle {

	private final UserServiceAsync m_userService;

	public UidSuggestOracle(final UserServiceAsync userService) {
		if (userService == null) {
			throw new IllegalArgumentException("userService cannot be null");
		}
		m_userService = userService;
	}

	public void requestSuggestions(final Request request, final Callback callback) {
		m_userService.suggestUid(request.getQuery(), new AsyncCallback() {
			public void onSuccess(final Object result) {
				final String[] users = (String[]) result;
				callback.onSuggestionsReady(request, new Response(newUserSuggestions(users)));
			}
			public void onFailure(final Throwable caught) { /* just ignore - there is nothing we can do */ }
		});
	}

	private Collection newUserSuggestions(final String[] users) {
		final ArrayList result = new ArrayList();
		for (int i = 0; i < users.length; i++) {
			final String user = users[i];
			result.add(new SuggestOracle.Suggestion() {
				public String getDisplayString() {
					return user;
				}
				public String getReplacementString() {
					return user;
				};
			});
		}
		return result;
	}

}
